/*!
 * Page: mine/setting/Setting
 * License: MIT
 * Created: 2019-09-17 14:21
 */

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { uploadFile } from '/api/file'
import { mallApi } from '/api/mall'
import { userApi } from '/api/user'
import { checkAuth, getDomoUser } from '/store/actions'
import { getServer, isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'
Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    user: {} as DomoUser,
    form: {
      name: '' as string,
      bio: '' as string,
      location: '' as string,
      play_position: '' as string,
      height: '' as string,
      weight: '' as string,
      sex: 0,
    },
    sex: 0,
    play_position: '' as string,
    canSubmit: false,
    region: [],
    submitting: false,
    avatar: '' as string,
    systemInfo: '' as string,
    show: false,
    avatarParams: {
      width: 300,
      height: 300,
      max_width: 500,
      max_height: 500,
      min_width: 250,
      min_height: 250,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      scale: 1,
      imgSrc: '' as any,
    },
    WxParams: {
      width: 300,
      height: 300,
      max_width: 500,
      max_height: 500,
      min_width: 250,
      min_height: 250,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
      imgSrc: '' as any,
    },
    cropper: '' as any,
    userTags: [],
    wxcropper: '' as any,
    wechat: '' as string,

    info: {} as any,
  },
  async onLoad() {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      // @ts-ignore
      cropper: this.selectComponent('#image-cropper-avatar'),
      // @ts-ignore
      wxcropper: this.selectComponent('#wx-cropper'),
    })
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          systemInfo: res.platform,
        })
      },
    })
    $event.on('after:login', this, async () => {
      this.getUserInfo()
    })
    $event.on('logged', this, async () => {
      this.getUserInfo()
    })
    if (!isLogin()) {
      await checkAuth()
    }
    this.getUserInfo()
    this.getUserTags()
  },
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      show: false,
    })
  },
  cancelWx() {
    this.setData({
      WxParams: {
        ...this.data.WxParams,
        show: false,
        src: '',
      },
    })
  },
  submitAvatar() {
    wx.showModal({
      title: '确认上传头像吗?',
      content: '确认会直接更换现在已有的头像信息',
      confirmText: '确认',
      cancelText: '不上传',
      success: ({ confirm, cancel }: { confirm?: boolean; cancel?: boolean }) => {
        if (confirm) {
          this.data.cropper.getImg(async (obj: any) => {
            try {
              const res = await uploadFile(obj.url)
              wx.showLoading({
                title: '上传中...',
              })
              userApi.saveUserInfo({ avatar: res }).then(() => {
                this.setData({ show: false })
                getDomoUser()
                wx.showToast({
                  title: '头像更新成功',
                })
                wx.hideLoading()
              })
            } catch (err) {
              this.handleError(err)
            }
          })
        }
      },
      fail: (err) => {
        this.handleError(err)
      },
    })
  },
  handleError(err: any) {
    wx.showToast({ title: `${getMessage(err.data).getMessage()}`, icon: 'none' })
    this.setData({ show: false })
  },
  handleAvatarTap() {
    wx.chooseImage({
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          avatarParams: {
            ...this.data.avatarParams,
            src: path,
          },
          show: true,
        })
      },
    })
  },
  submitWx() {
    wx.showModal({
      title: '确认上传微信二维码吗?',
      content: '确认会直接更换现在已有的二维码',
      confirmText: '确认',
      cancelText: '不上传',
      success: ({ confirm, cancel }: { confirm?: boolean; cancel?: boolean }) => {
        if (confirm) {
          this.data.wxcropper.getImg(async (obj: any) => {
            try {
              const res = await uploadFile(obj.url)
              wx.showLoading({
                title: '上传中...',
              })
              mallApi
                .saveShoperInfo({ qrCode: res, weChat: this.data.wechat })
                .then(() => {
                  this.cancelWx()
                  getDomoUser()
                  wx.showToast({
                    title: '二维码更新成功',
                  })
                  wx.hideLoading()
                })
                .catch((err) => {
                  this.handleError(err)
                })
            } catch (err) {
              this.handleError(err)
            }
          })
        }
      },
      fail: (err: any) => {
        this.handleError(err)
      },
    })
  },
  handleHeightConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData(
      {
        form: {
          ...this.data.form,
          height: value,
        },
      },
      () => {
        this.canSubmit()
      },
    )
  },
  handleWeightConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData(
      {
        form: {
          ...this.data.form,
          weight: value,
        },
      },
      () => {
        this.canSubmit()
      },
    )
  },
  handleWxTap() {
    wx.chooseImage({
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          WxParams: {
            ...this.data.WxParams,
            src: path,
            show: true,
          },
        })
      },
    })
  },
  /**
   * 获取用户信息及用户圈子
   */
  async getUserInfo() {
    const server = getServer()
    const info = await mallApi.getShoperInfo()
    const user = wx.getStorageSync(`${server}/logged`).data || {}
    this.setData({
      user,
      form: {
        name: user.name,
        play_position: user.play_position,
        sex: user.sex,
        bio: user.bio,
        height: user.height,
        weight: user.weight,
        location: user.location,
      },
      info,
      wechat: info.weChat ? info.weChat : '',
      WxParams: {
        ...this.data.WxParams,
        imgSrc: info.qrCode ? info.qrCode.url : '',
      },
      canSubmit: false,
      region: user.location ? user.location.split(' ') : '',
      avatar: user.avatar.url ? user.avatar.url : user.avatar,
    })
  },
  handlePlayPositionConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData(
      {
        form: {
          ...this.data.form,
          play_position: value,
        },
      },
      () => {
        this.canSubmit()
      },
    )
  },
  handleNameConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData(
      {
        form: {
          ...this.data.form,
          name: value,
        },
      },
      () => {
        this.canSubmit()
      },
    )
  },
  handleWechatConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData({
      wechat: value,
    })
    this.canSubmit()
  },
  handleBioConfirm({ detail: { value } }: { value: string; detail: any }) {
    this.setData(
      {
        form: {
          ...this.data.form,
          bio: value,
        },
      },
      () => {
        this.canSubmit()
      },
    )
  },

  canSubmit() {
    const {
      data: { user, form, info, wechat },
    } = this
    this.setData({
      canSubmit:
        user.bio !== form.bio ||
        user.name !== form.name ||
        user.location !== form.location ||
        user.sex !== form.sex ||
        (info && info.wechat !== wechat),
    })
  },
  /** 修改性别 */
  changeSex() {
    const _this = this
    wx.showActionSheet({
      itemList: ['男', '女', '保密'],
      success(res: { tapIndex: number }) {
        _this.setData(
          {
            form: {
              ..._this.data.form,
              sex: res.tapIndex === 0 ? 1 : res.tapIndex === 1 ? 2 : 0,
            },
          },
          () => {
            _this.canSubmit()
          },
        )
      },
    })
  },
  /**
   * 地区选择
   */
  bindRegionChange: function (e: any) {
    const region = e.detail.value.filter((i: string) => i !== '全部')
    if (region.length < 2) {
      wx.showModal({
        title: '提示',
        content: '请至少选择省市',
        showCancel: false,
      })
      return
    }
    this.setData(
      {
        form: {
          ...this.data.form,
          location: region.join(' '),
        },
        region,
      },
      () => {
        this.canSubmit()
      },
    )
  },

  async doSubmit() {
    const {
      data: { form, submitting, info, wechat },
    } = this
    if (!submitting) {
      this.setData({
        submitting: true,
      })
      userApi
        .saveUserInfo(form)
        .then(async () => {
          if (info && info.wechat !== wechat) {
            await mallApi.saveShoperInfo({ weChat: wechat })
          }
        })
        .then(() => {
          this.setData(
            {
              submitting: false,
            },
            () => {
              wx.showToast({
                title: '成功',
              })
              getDomoUser()
            },
          )
        })
        .catch((err: any) => {
          this.setData({
            submitting: false,
          })
          wx.showToast({ title: `${getMessage(err.data).getMessage()}`, icon: 'none' })
        })
    }
  },
  /** 获取用户标签 */
  async getUserTags() {
    const userTags = await userApi.getUserTags()
    this.setData({
      userTags,
    })
  },
  /** 修改标签 */
  logs() {
    wx.navigateTo({
      url: '/mine/userTags/userTags',
    })
  },
})
